{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "from collections.abc import Iterable, Iterator\n",
    "\n",
    "a = [1, 2]\n",
    "iter_rator = iter(a)\n",
    "print(isinstance(a, Iterable))\n",
    "print(isinstance(iter_rator, Iterator))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tom\n",
      "bob\n",
      "jane\n"
     ]
    }
   ],
   "source": [
    "class Company:\n",
    "    def __init__(self, employee_list):\n",
    "        self.employee = employee_list\n",
    "    \n",
    "    def __getitem__(self, item):\n",
    "        return self.employee[item]\n",
    "    \n",
    "    \n",
    "if __name__ == \"__main__\":\n",
    "    company = Company(['tom', 'bob', 'jane'])\n",
    "    for item in company:\n",
    "        print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 迭代器设计模式\n",
    "\n",
    "from collections.abc import Iterator\n",
    "\n",
    "class Company:\n",
    "    def __init__(self, employee_list):\n",
    "        self.employee = employee_list\n",
    "    \n",
    "    def __iter__(self):\n",
    "        return MyIterator(self.employee)\n",
    "\n",
    "class MyIterator(Iterator):\n",
    "    def __init__(self, employee_list):\n",
    "        self.iter_list = employee_list\n",
    "        # 迭代器游标初始化\n",
    "        self.index = 0\n",
    "    \n",
    "    def __next__(self):\n",
    "        try:\n",
    "            word = self.iter_list[self.index]\n",
    "        except IndexError as e:\n",
    "            raise StopIteration\n",
    "        self.index += 1\n",
    "        return word\n",
    "    \n",
    "if __name__ == \"__main__\":\n",
    "    company = Company(['tom', 'bob', 'jane'])\n",
    "    my_itor = iter(company)\n",
    "    while True:\n",
    "        try:\n",
    "            result = next(my_itor)\n",
    "            print(result)\n",
    "        except StopIteration as e:\n",
    "            break\n",
    "\n",
    "#     for item in company:\n",
    "#         print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
